package com.ruoyi.yipaiju.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.constant.BizConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.enums.dict.ForeclosedHouseStatus;
import com.ruoyi.common.enums.dict.OriginName;
import com.ruoyi.common.enums.dict.ServerGrabMold;
import com.ruoyi.common.enums.dict.ServerStatus;
import com.ruoyi.common.utils.CurrencyUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.http.HttpRespons;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.yipaiju.domain.ServerManage;
import com.ruoyi.yipaiju.domain.SpiderHouse;
import com.ruoyi.yipaiju.mapper.ServerManageMapper;
import com.ruoyi.yipaiju.service.IServerManageService;
import com.ruoyi.yipaiju.service.ISpiderHouseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.QueueInformation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 服务器Service业务层处理
 * 
 * @author liuwp
 * @date 2023-06-19
 */
@Service
public class ServerManageServiceImpl implements IServerManageService 
{
    private static final Logger logger = LoggerFactory.getLogger(ServerManageServiceImpl.class);

    @Autowired
    private ServerManageMapper serverManageMapper;
    @Autowired
    private ISpiderHouseService spiderHouseService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpAdmin amqpAdmin;

    /**
     * 查询服务器
     * 
     * @param id 服务器主键
     * @return 服务器
     */
    @Override
    public ServerManage selectServerManageById(Long id)
    {
        return serverManageMapper.selectServerManageById(id);
    }

    /**
     * 查询服务器列表
     * 
     * @param serverManage 服务器
     * @return 服务器
     */
    @Override
    public List<ServerManage> selectServerManageList(ServerManage serverManage)
    {
        return serverManageMapper.selectServerManageList(serverManage);
    }

    /**
     * 根据业务主键查询一条记录：服务器
     *
     * @param serverManage 服务器
     * @return 服务器
     */
    @Override
    public ServerManage selectOneServerManage(ServerManage serverManage)
    {
        return serverManageMapper.selectOneServerManage(serverManage);
    }

    /**
     * 新增服务器
     * 
     * @param serverManage 服务器
     * @return 结果
     */
    @Override
    public int insertServerManage(ServerManage serverManage)
    {
        return serverManageMapper.insertServerManage(serverManage);
    }

    /**
     * 修改服务器
     * 
     * @param serverManage 服务器
     * @return 结果
     */
    @Override
    public int updateServerManage(ServerManage serverManage)
    {
        return serverManageMapper.updateServerManage(serverManage);
    }

    @Override
    public int updateServerManageCondition(ServerManage serverManage, ServerManage serverManageCondition)
    {
        return serverManageMapper.updateServerManageCondition(serverManage, serverManageCondition);
    }

    /**
     * 批量删除服务器
     * 
     * @param ids 需要删除的服务器主键
     * @return 结果
     */
    @Override
    public int deleteServerManageByIds(Long[] ids)
    {
        return serverManageMapper.deleteServerManageByIds(ids);
    }

    /**
     * 删除服务器信息
     * 
     * @param id 服务器主键
     * @return 结果
     */
    @Override
    public int deleteServerManageById(Long id)
    {
        return serverManageMapper.deleteServerManageById(id);
    }

    /**
     * 条件删除服务器
     *
     * @param serverManage 服务器
     * @return 结果
     */
    @Override
    public int deleteServerManageByCondition(ServerManage serverManage)
    {
        return serverManageMapper.deleteServerManageByCondition(serverManage);
    }

    @Override
    public int serverAddProv(ServerManage serverManage) {
        if (serverManage != null && StringUtils.isNotEmpty(serverManage.getGrabProvince())){
            serverManage.setGrabProvince(serverManage.getGrabProvince().replace("，", ","));
//            String sdkPath = BizConstants.Spider.SDK_PATH;
//            String codePath = BizConstants.Spider.CODE_PATH;
//            sdkPath = StringUtils.isNotEmpty(serverManage.getSdkPath()) ? serverManage.getSdkPath(): sdkPath;
//            codePath = StringUtils.isNotEmpty(serverManage.getCodePath()) ? serverManage.getCodePath() : codePath;
//            String command = sdkPath + " "+codePath+"/AddProv.py " + serverManage.getGrabProvince();
//            CurrencyUtil.remoteExecCmd(serverManage.getServerIp(), serverManage.getAccount(), serverManage.getPassword(), command);
//            return serverManage.getGrabProvince().split(",").length;

            String queueName = BizConstants.Spider.ALILQNAME + StringUtils.dreX(serverManage.getServerIp());
            for (String prov : serverManage.getGrabProvince().split(",")) {
                rabbitTemplate.convertAndSend(queueName, prov); // TODO 可以拼一个页数
            }

            return serverManage.getGrabProvince().split(",").length;
        }
        return 0;
    }

    @Override
    public int serverAddDetail(ServerManage serverManage, String queueName, Integer addNum, String origin) {
        if (serverManage != null){
            String lockUuid = IdUtils.randomUUID();
            // 根据服务器配置查询可调度的列表数据
            spiderHouseService.updateSpiderHouseListGrabing(Builder.of(SpiderHouse::new)
                    .with(SpiderHouse::setProvince, serverManage.getGrabProvince() != null ? serverManage.getGrabProvince().replace("，",",") : null)
                    .with(SpiderHouse::setCity, serverManage.getGrabCity() != null ? serverManage.getGrabCity().replace("，",",") : null)
                    .with(SpiderHouse::setStatus, serverManage.getGrabType() != null ? serverManage.getGrabType().replace("，",",") : null)
                    .with(SpiderHouse::setOrigin, origin)
                    .with(SpiderHouse::setLockUuid, lockUuid)
                    .with(SpiderHouse::setLimit, addNum)
                    .build());

            List<SpiderHouse> spiderHouses = spiderHouseService.selectSpiderHouseList(Builder.of(SpiderHouse::new).with(SpiderHouse::setLockUuid, lockUuid).build());

            queueName = queueName + StringUtils.dreX(serverManage.getServerIp());
            for (SpiderHouse spiderHouse : spiderHouses) {
                rabbitTemplate.convertAndSend(queueName, spiderHouse.getAuctionUrl()+"?"+spiderHouse.getId());
            }
            return spiderHouses.size();
        }
        return 0;
    }

    @Override
    public int serverQueueCount(String queueName) {
        QueueInformation queueInfo = amqpAdmin.getQueueInfo(queueName);
        if (queueInfo != null) {
            return queueInfo.getMessageCount();
        }
        return 0;
    }

    @Override
    public boolean serverClearQueue(String queueName) {
        try {
            Channel channel = rabbitTemplate.getConnectionFactory().createConnection().createChannel(false);
            channel.queuePurge(queueName);
            channel.close();
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean serverSpiderArrange(ServerManage serverManage) {
        if (serverManage != null){
            String codePath = BizConstants.Spider.CODE_PATH;
            codePath = StringUtils.isNotEmpty(serverManage.getCodePath()) ? serverManage.getCodePath() : codePath;
            File file = new File(codePath);
            String command = file.getParent() + "/Update.bat";
            String result = CurrencyUtil.remoteExecCmd(serverManage.getServerIp(), serverManage.getAccount(), serverManage.getPassword(), command);
            if (result != null && result.length() > 10){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean spiderStart(ServerManage serverManage) {
        if (serverManage != null){
//            String command = "taskkill /F /IM python.exe";
//            String result = CurrencyUtil.remoteExecCmd(serverManage.getServerIp(), serverManage.getAccount(), serverManage.getPassword(), command);
//            if (StringUtils.isNotEmpty(result) && result.length() > 10){
//                return true;
//            }
        }
        return false;
    }

    @Override
    public boolean spiderShutdown(ServerManage serverManage) {
        if (serverManage != null){
            String command = "taskkill /F /IM python.exe";
            String result = CurrencyUtil.remoteExecCmd(serverManage.getServerIp(), serverManage.getAccount(), serverManage.getPassword(), command);
            if (StringUtils.isNotEmpty(result) && result.length() > 10){
                return true;
            }
        }
        return false;
    }

    @Override
    public void serverSynchQueue(ServerManage serverManage){
        int provCount = serverQueueCount(BizConstants.Spider.ALILQNAME+StringUtils.dreX(serverManage.getServerIp()));
        serverManage.setQueueProvCount(provCount);
        int detailCount = serverQueueCount(BizConstants.Spider.ALIDQNAME+StringUtils.dreX(serverManage.getServerIp()));
        serverManage.setQueueDetailCount(detailCount);
        int jdDetailCount = serverQueueCount(BizConstants.Spider.JDDQNAME+StringUtils.dreX(serverManage.getServerIp()));
        serverManage.setQueueDetailCountJd(jdDetailCount);
        int gpwDetailCount = serverQueueCount(BizConstants.Spider.GPWDQNAME+StringUtils.dreX(serverManage.getServerIp()));
        serverManage.setQueueDetailCountGpw(gpwDetailCount);
        int zpptDetailCount = serverQueueCount(BizConstants.Spider.ZPPTDQNAME+StringUtils.dreX(serverManage.getServerIp()));
        serverManage.setQueueDetailCountZppt(zpptDetailCount);
        int sszcwDetailCount = serverQueueCount(BizConstants.Spider.SSZCWDQNAME+StringUtils.dreX(serverManage.getServerIp()));
        serverManage.setQueueDetailCountSszcw(sszcwDetailCount);
        int icbcDetailCount = serverQueueCount(BizConstants.Spider.ICBCDQNAME+StringUtils.dreX(serverManage.getServerIp()));
        serverManage.setQueueDetailCountIcbc(icbcDetailCount);
        int cbexDetailCount = serverQueueCount(BizConstants.Spider.CBEXDQNAME+StringUtils.dreX(serverManage.getServerIp()));
        serverManage.setQueueDetailCountCbex(cbexDetailCount);
        updateServerManage(serverManage);
    }

    @Override
    public void serverAddprovDispatch() {
        // 获取可用的服务器
        List<ServerManage> serverManages = selectServerManageList(new ServerManage());
        for (ServerManage serverManage : serverManages) {
            try {
                if (serverManage.getStatus().intValue() != ServerStatus.STOP.getValue()){
                    if (serverManage.getGrabMold() == null || serverManage.getGrabMold().contains(ServerGrabMold.LIST.getValue().toString())){
                        // 获取队列数量 如果太多了就不加了
                        int queueCount = serverQueueCount(BizConstants.Spider.ALILQNAME + StringUtils.dreX(serverManage.getServerIp()));
                        int addNum = 0;
                        // 数量小于最大值时才加  否则就不加了
                        if (queueCount < BizConstants.Spider.QUEUE_LIST_MAX_NUM && StringUtils.isNotEmpty(serverManage.getGrabProvince())){
                            addNum = serverAddProv(serverManage);
                        }
                        serverManage.setQueueProvCount(queueCount + addNum);
                        updateServerManage(serverManage);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void serverAdddetailDispatchAll(){
        // 获取可用的服务器
        List<ServerManage> serverManages = selectServerManageList(new ServerManage());
        for (ServerManage serverManage : serverManages) {
            serverAdddetailDispatchItem(serverManage);
        }

    }

    @Override
    public void serverAdddetailDispatchItem(ServerManage serverManage) {
        try {
            if (serverManage.getStatus().intValue() != ServerStatus.STOP.getValue()){
                if (serverManage.getGrabMold() != null){
                    if (serverManage.getGrabMold().contains(ServerGrabMold.ALIDETAIL.getValue().toString())){
                        int count = detailQueueAdd(serverManage, BizConstants.Spider.ALIDQNAME, BizConstants.Spider.QUEUE_DETAIL_MAX_NUM_ALI, OriginName.ALI.getValue());
                        serverManage.setQueueDetailCount(count);
                    }
                    if (serverManage.getGrabMold().contains(ServerGrabMold.JDDETAIL.getValue().toString())){
                        int count = detailQueueAdd(serverManage, BizConstants.Spider.JDDQNAME, BizConstants.Spider.QUEUE_DETAIL_MAX_NUM_JD, OriginName.JD.getValue());
                        serverManage.setQueueDetailCountJd(count);
                    }
                    if (serverManage.getGrabMold().contains(ServerGrabMold.GPWDETAIL.getValue().toString())){
                        int count = detailQueueAdd(serverManage, BizConstants.Spider.GPWDQNAME, BizConstants.Spider.QUEUE_DETAIL_MAX_NUM_GPW, OriginName.GPW.getValue());
                        serverManage.setQueueDetailCountGpw(count);
                    }
                    if (serverManage.getGrabMold().contains(ServerGrabMold.ZPPTDETAIL.getValue().toString())){
                        int count = detailQueueAdd(serverManage, BizConstants.Spider.ZPPTDQNAME, BizConstants.Spider.QUEUE_DETAIL_MAX_NUM_ZPPT, OriginName.ZPPT.getValue());
                        serverManage.setQueueDetailCountZppt(count);
                    }
                    if (serverManage.getGrabMold().contains(ServerGrabMold.SSZCWDETAIL.getValue().toString())){
                        int count = detailQueueAdd(serverManage, BizConstants.Spider.SSZCWDQNAME, BizConstants.Spider.QUEUE_DETAIL_MAX_NUM_SSZCW, OriginName.SSZCW.getValue());
                        serverManage.setQueueDetailCountSszcw(count);
                    }
                    if (serverManage.getGrabMold().contains(ServerGrabMold.ICBCDETAIL.getValue().toString())){
                        int count = detailQueueAdd(serverManage, BizConstants.Spider.ICBCDQNAME, BizConstants.Spider.QUEUE_DETAIL_MAX_NUM_ICBC, OriginName.ICBC.getValue());
                        serverManage.setQueueDetailCountIcbc(count);
                    }
                    if (serverManage.getGrabMold().contains(ServerGrabMold.CBEXDETAIL.getValue().toString())){
                        int count = detailQueueAdd(serverManage, BizConstants.Spider.CBEXDQNAME, BizConstants.Spider.QUEUE_DETAIL_MAX_NUM_CBEX, OriginName.CBEX.getValue());
                        serverManage.setQueueDetailCountCbex(count);
                    }
                    updateServerManage(serverManage);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public int detailQueueAdd(ServerManage serverManage, String queueName, int maxCount, String originName){
        int queueCount = serverQueueCount(queueName + StringUtils.dreX(serverManage.getServerIp()));
        int addNum = 0;
        // 数量小于最大值时才加  否则就不加了
        if (queueCount < maxCount){
            addNum = serverAddDetail(serverManage, queueName, maxCount, originName);
        }
        return queueCount + addNum;
    }

    @Override
    public void serverSynchQueueCount() {
        // 获取可用的服务器
        List<ServerManage> serverManages = selectServerManageList(new ServerManage());
        for (ServerManage serverManage : serverManages) {
            if (serverManage.getStatus().intValue() != ServerStatus.STOP.getValue()){
                serverSynchQueue(serverManage);
            }
        }
    }

    @Override
    public void serverJdAuctionListSynch(Double pageRate) {
        String houseTypes = "101,102,103,104";
        int page = 1;
        int pageSize = 40;

        for (String houseType : houseTypes.split(",")) {
            int totalNum = call_jd(page, pageSize, houseType);
            // 计算总页数
            int totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;
            if (pageRate != null){
                totalPage = (int) (totalPage * pageRate);
            }
            for (int i = 1; i < totalPage; i++) {
                call_jd(i+1, pageSize, houseType);
            }
        }
    }

    @Override
    public void serverGpwAuctionListSynch(Double pageRate) {

        // 拍品类型就是 itemType = 1 是房产
        String houseTypes = "1";
        int page = 1;
        int pageSize = 20;   // 尽量和网站一样  万一给控制了麻烦。。。

        for (String houseType : houseTypes.split(",")) {
            int totalNum = call_gpw(page, pageSize, houseType);
            // 计算总页数
            int totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;
            if (pageRate != null){
                totalPage = (int) (totalPage * pageRate);
            }
            for (int i = 1; i < totalPage; i++) {
                call_gpw(i+1, pageSize, houseType);
            }
        }
    }

    @Override
    public void serverZpptAuctionListSynch(Double pageRate) {

        //secondaryType=1 住宅
        //secondaryType=2 工业
        //secondaryType=3 商业
        //secondaryType=4 其他
//        https://paimai.caa123.org.cn/paimai-web/ws/0.1/lots?start=1&count=20&standardType=6&secondaryType=1&time=1689342829953&_=1689342829886

        String houseTypes = "1,2,3,4";
        int page = 1;
        int pageSize = 20;   // 尽量和网站一样  万一给控制了麻烦。。。

        for (String houseType : houseTypes.split(",")) {
            int totalNum = call_zppt(page, pageSize, houseType);
            // 计算总页数
            int totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;
            if (pageRate != null){
                totalPage = (int) (totalPage * pageRate);
            }
            for (int i = 1; i < totalPage; i++) {
                call_zppt(i+1, pageSize, houseType);
            }
        }
    }

    @Override
    public void cleanSpiderListCityEtc() {
        ServerManage serverManage = new ServerManage();
        serverManage.setGrabMold("1");
        List<ServerManage> serverManages = selectServerManageList(serverManage);
        for (ServerManage manage : serverManages) {
            manage.setGrabCity("");
            manage.setGrabDistrict("");
            manage.setGrabPage("");
            manage.setHouseType("");
            updateServerManage(manage);
        }
    }


    public int call_jd(int page, int pageSize, String houseType){
        try {

            // 广东 广州市 海珠区  provinceId":19,"cityId":1601,"countyId":3634
//            https://api.m.jd.com/api?appid=paimai&functionId=paimai_unifiedSearch&body=%7B%22investmentType%22%3A%22%22%2C%22apiType%22%3A12%2C%22page%22%3A1%2C%22pageSize%22%3A40%2C%22keyword%22%3A%22%22%2C%22provinceId%22%3A19%2C%22cityId%22%3A1601%2C%22countyId%22%3A3634%2C%22multiPaimaiStatus%22%3A%22%22%2C%22multiDisplayStatus%22%3A%22%22%2C%22multiPaimaiTimes%22%3A%22%22%2C%22childrenCateId%22%3A%22101%22%2C%22currentPriceRangeStart%22%3A%22%22%2C%22currentPriceRangeEnd%22%3A%22%22%2C%22timeRangeTime%22%3A%22endTime%22%2C%22timeRangeStart%22%3A%22%22%2C%22timeRangeEnd%22%3A%22%22%2C%22loan%22%3A%22%22%2C%22purchaseRestriction%22%3A%22%22%2C%22orgId%22%3A%22%22%2C%22orgType%22%3A%22%22%2C%22sortField%22%3A8%2C%22projectType%22%3A1%2C%22reqSource%22%3A0%2C%22labelSet%22%3A%22%22%2C%22publishSource%22%3A%22%22%7D&clientVersion=paimai-h5-1.0.0&client=paimai-h5&t=1690449579226&h5st=20230727171939257%3B0039417993556085%3B106e8%3Btk03wc0971d2118nVWbuxuFMYi4MQj2mlIzfBMlQ16aw1ASMHAeOUaddCvBGviEHeVnWuqNgLtV5RSwhL2rwaCuzcOnP%3B7a1931780acffa0f276afa250e561e5f50596b8eca0cb4fd0c797784f27deacd%3B3.1%3B1690449579257%3B24c9ee85e67cf80746dd82817ecbeafc7a829b35c7f446a4c7d476cc9faa1d8834a93323ad7bce9bef1bba682b93d2e355076cc27b11bb228be53f32ed20565283152a6b7df59cfc9318aa8e59b5a0868a855e5b4bb9ab9cad6a7b49e28f3e3fe43d307c02f3fc6e7850f200b95aa812fa4b8bf459470202453fc0c8d6ff9ce7&x-api-eid-token=jdd03N6BR43SWR4ULH2PLEEWIT7KVASJAAZAKOLRMGMD3NCZVDMVHWXIXJ6DPUFRP2RH2KHA3Q4QSS6ODNURRP3KM7W6LXQAAAAMJSYO3NSQAAAAADTBRW7VDJNWI3AX

//            String body = "{\"investmentType\":\"\",\"apiType\":12,\"page\":"+page+",\"pageSize\":"+pageSize+",\"keyword\":\"\",\"provinceId\":\"\",\"cityId\":\"\",\"countyId\":\"\",\"multiPaimaiStatus\":\"\",\"multiDisplayStatus\":\"\",\"multiPaimaiTimes\":\"\",\"childrenCateId\":\""+houseType+"\",\"currentPriceRangeStart\":\"\",\"currentPriceRangeEnd\":\"\",\"timeRangeTime\":\"endTime\",\"timeRangeStart\":\"\",\"timeRangeEnd\":\"\",\"loan\":\"\",\"purchaseRestriction\":\"\",\"orgId\":\"\",\"orgType\":\"\",\"sortField\":8,\"projectType\":1,\"reqSource\":0,\"labelSet\":\"\",\"publishSource\":\"\"}";
            String body = "{\"investmentType\":\"\",\"apiType\":12,\"page\":"+page+",\"pageSize\":"+pageSize+",\"keyword\":\"\",\"provinceId\":19,\"cityId\":\"\",\"countyId\":\"\",\"multiPaimaiStatus\":\"\",\"multiDisplayStatus\":\"\",\"multiPaimaiTimes\":\"\",\"childrenCateId\":\""+houseType+"\",\"currentPriceRangeStart\":\"\",\"currentPriceRangeEnd\":\"\",\"timeRangeTime\":\"endTime\",\"timeRangeStart\":\"\",\"timeRangeEnd\":\"\",\"loan\":\"\",\"purchaseRestriction\":\"\",\"orgId\":\"\",\"orgType\":\"\",\"sortField\":8,\"projectType\":1,\"reqSource\":0,\"labelSet\":\"\",\"publishSource\":\"\"}";

//            String url = "https://api.m.jd.com/api?appid=paimai&functionId=paimai_unifiedSearch&body="+ URLEncoder.encode(body, "utf-8")+"&clientVersion=paimai-h5-1.0.0&client=paimai-h5&t="+System.currentTimeMillis()+"&h5st="+DateUtils.dateTimeNow("yyyyMMddHHmmssSSS")+"%3B0039417993556085%3B106e8%3Btk03wc0971d2118nVWbuxuFMYi4MQj2mlIzfBMlQ16aw1ASMHAeOUaddCvBGviEHeVnWuqNgLtV5RSwhL2rwaCuzcOnP%3B612fb469f7c007fe632c414cb3f531bd710cf0699a40f8e1a38e368192e0bef4%3B3.1%3B1690442104179%3B24c9ee85e67cf80746dd82817ecbeafc7a829b35c7f446a4c7d476cc9faa1d8834a93323ad7bce9bef1bba682b93d2e355076cc27b11bb228be53f32ed20565283152a6b7df59cfc9318aa8e59b5a0868a855e5b4bb9ab9cad6a7b49e28f3e3fe43d307c02f3fc6e7850f200b95aa812fa4b8bf459470202453fc0c8d6ff9ce7&x-api-eid-token=jdd03EU7PJ4SNO3N5D6MIMMMBBHVWL62CDFTT3V22SFVEEIYPYM5Z4UPY5CH3ULATT6F2ZMFGIOAXQR4DCUPV4SIF57XJHAAAAAMQ5R76U3QAAAAACRA3OSQPSELQKIX";

           String url =  "https://api.m.jd.com/api?appid=paimai&functionId=paimai_unifiedSearch&body="+ URLEncoder.encode(body, "utf-8")+"&clientVersion=paimai-h5-1.0.0&client=paimai-h5&t="+System.currentTimeMillis()+"&h5st="+DateUtils.dateTimeNow("yyyyMMddHHmmssSSS")+"%3Biy6nmtzz9iggzzz9%3B106e8%3Btk03w81bf1b5c18nV9EFij3kOI1fTLfF85AiIIb83VkirLeBw5VpkH6sa2Ks-KanQpznpquAbUS0T1XMQPrX5CTYV92e%3B93b8477a0d2c001bfc83e75fca92285b%3B4.7%3B1725002839531%3BUO2ISj3C5rqgUF5CFxP3zn4sn_i_BRWelhO8-7McQTaH3fxk5OsBdkEK1lqX72oZO_LBTExzUlLH5EBWJUFSP99P1fSr43A-4oFB2S4HC3iUYq8O7ja9cHCxovy6iiMhASNWdKTE7w9IqLu2T-52ajhgG9nPfzqsazvCEZWiM8FUQzj4mdozlLG2jCEVmGy1YZO-iNMi4CMUPOD5dEnwhFpLaastMLfjlWiouziIBjdO9B_Bkpiz3w6LyUE59mwpE690HFEzq4gBUxPQXrWfXb2A2a56nBFNQSlsDoaBPicMykR-a5EwLepPUvdFZj2vuTPLEyjAhstyDFvNXCfAGZlTvDA_4nhbzUHlhTJdBT9UeYVYfwItBnB1AuHoQh-d6-AlM3iatiVIbYksdUh_VwFRUpJ7luwhRkLnI8eP6sKgw_4OatZ6HfydQYi92ILAXorbapzB8FkFuT08sJ7gHA8yzHQwac8v4g-P-2w_UBga-1wN4TbZrP5Apb_Xcg0PVys2JbAr_Mih9e5y4AbiQ6ySjC5yrrkJwiITE-u2CTfAV1m71C5l_0R_juS8RU4yozP8fY_p5xIpUsrVxOLCu7nZggE7nDk8PeheJO0dl8zjLad9Prk3hGJ0DQIeqffFGvzEemLTD52YgeDqWQHLXbk3%3Bc0380f5225ab40e672dbdba4a1859b7c&x-api-eid-token=jdd03A2GVY6PI7LZ4JX4MNEWJVNPDRUU2X3RWULXOASM3265R2OIU3XCC6TOFKHPVDCZECBQ6KCPAXXM74ENDJVZ5BA2YKYAAAAMRUIVVZGAAAAAACSFI6QPMGQ3QSEX";
//
//
//            String url = "https://api.m.jd.com/api?appid=paimai&functionId=paimai_unifiedSearch&body="+ URLEncoder.encode(body, "utf-8")+"&clientVersion=paimai-h5-1.0.0&client=paimai-h5&t=1688093465907&h5st=20230630105105935%3B0039417993556085%3B106e8%3Btk03waed61c0918nt1IboQ7WNUPnqswcfOWhh18jSkgH73gg5ashT8MNJnW36wOUmXZOM9MQH4nTNw7WCRYVYRqw7g-w%3B26bc279e2d5c048e445327476a6c3aa21d19d7dfbd7afef4cf09fe5e5bd96d2f%3B3.1%3B1688093465935%3B24c9ee85e67cf80746dd82817ecbeafc7a829b35c7f446a4c7d476cc9faa1d8834a93323ad7bce9bef1bba682b93d2e3938e6fdf0b116e62557e4895c51d3caa8f37f0f43c683675e058de07d25d6a4ac2f7032fdaa2bd23286ee4fe08a60cdb&x-api-eid-token=jdd03N6BR43SWR4ULH2PLEEWIT7KVASJAAZAKOLRMGMD3NCZVDMVHWXIXJ6DPUFRP2RH2KHA3Q4QSS6ODNURRP3KM7W6LXQAAAAMJBIPKSCAAAAAACOA424NLSE7PYIX";

//            https://api.m.jd.com/api?appid=paimai&functionId=paimai_unifiedSearch&body=%7B%22investmentType%22%3A%22%22%2C%22apiType%22%3A12%2C%22page%22%3A1%2C%22pageSize%22%3A40%2C%22keyword%22%3A%22%22%2C%22provinceId%22%3A%22%22%2C%22cityId%22%3A%22%22%2C%22countyId%22%3A%22%22%2C%22multiPaimaiStatus%22%3A%22%22%2C%22multiDisplayStatus%22%3A%22%22%2C%22multiPaimaiTimes%22%3A%22%22%2C%22childrenCateId%22%3A%22101%22%2C%22currentPriceRangeStart%22%3A%22%22%2C%22currentPriceRangeEnd%22%3A%22%22%2C%22timeRangeTime%22%3A%22endTime%22%2C%22timeRangeStart%22%3A%22%22%2C%22timeRangeEnd%22%3A%22%22%2C%22loan%22%3A%22%22%2C%22purchaseRestriction%22%3A%22%22%2C%22orgId%22%3A%22%22%2C%22orgType%22%3A%22%22%2C%22sortField%22%3A8%2C%22projectType%22%3A1%2C%22reqSource%22%3A0%2C%22labelSet%22%3A%22%22%2C%22publishSource%22%3A%22%22%7D&clientVersion=paimai-h5-1.0.0&client=paimai-h5&t=1688093465907&h5st=20230630105105935%3B0039417993556085%3B106e8%3Btk03waed61c0918nt1IboQ7WNUPnqswcfOWhh18jSkgH73gg5ashT8MNJnW36wOUmXZOM9MQH4nTNw7WCRYVYRqw7g-w%3B26bc279e2d5c048e445327476a6c3aa21d19d7dfbd7afef4cf09fe5e5bd96d2f%3B3.1%3B1688093465935%3B24c9ee85e67cf80746dd82817ecbeafc7a829b35c7f446a4c7d476cc9faa1d8834a93323ad7bce9bef1bba682b93d2e3938e6fdf0b116e62557e4895c51d3caa8f37f0f43c683675e058de07d25d6a4ac2f7032fdaa2bd23286ee4fe08a60cdb&x-api-eid-token=jdd03N6BR43SWR4ULH2PLEEWIT7KVASJAAZAKOLRMGMD3NCZVDMVHWXIXJ6DPUFRP2RH2KHA3Q4QSS6ODNURRP3KM7W6LXQAAAAMJBIPKSCAAAAAACOA424NLSE7PYIX

            HttpRequest httpRequest = new HttpRequest();
            HttpRespons httpRespons = httpRequest.sendGet(url);
//            logger.info("call_jd-content="+httpRespons.getContent());
            if (httpRespons != null && httpRespons.getContent() != null){
                int c = 0;
                while (true){
                    if (httpRespons.getCode() != HttpStatus.SUCCESS){
                        httpRespons = httpRequest.sendGet(url);
                        Thread.sleep(500);
                        c++;
                        if (c > 100){
                            break;
                        }
                    }else {
                        break;
                    }
                }

                JSONObject jsonObject = JSONObject.parseObject(httpRespons.getContent());
                if (jsonObject.containsKey("code") && jsonObject.getIntValue("code") == 0){
                    logger.info("同步京东列表接口调用成功 page="+page+",pageSize="+pageSize+",houseType="+houseType);
                    JSONArray jsonArray = (JSONArray) CurrencyUtil.readJson(jsonObject, "datas");

                    List<SpiderHouse> spiderHouses = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject item = jsonArray.getJSONObject(i);
                        SpiderHouse spiderHouse = new SpiderHouse();
                        spiderHouse.setHouseCode(item.getString("id"));
                        spiderHouse.setProvince(item.getString("province"));
                        spiderHouse.setCity(item.getString("city").replace("市", ""));
                        spiderHouse.setAuctionUrl("https://paimai.jd.com/"+spiderHouse.getHouseCode());
                        spiderHouse.setStatus(houseStatusJdHandle(item.getIntValue("auctionStatus"), item.getIntValue("displayStatus"), item.getIntValue("bidCount")));
                        spiderHouse.setHouseType(houseTypeJdHandle(houseType));

                        spiderHouse.setOrigin(OriginName.JD.getValue());
                        spiderHouse.setAssessmentPrice(item.getLong("assessmentPrice"));
                        spiderHouse.setCurrentPrice(item.getLong("currentPrice"));
                        spiderHouse.setDiscountRate(item.getBigDecimal("discountRate"));
                        spiderHouse.setEnsurePrice(item.getLong("ensurePrice"));
                        spiderHouse.setMarketPrice(item.getLong("marketPrice"));
                        spiderHouse.setMinPrice(item.getLong("minPrice"));
                        spiderHouse.setAddress(item.getString("productAddress"));
                        spiderHouse.setCourt(item.getString("shopName"));
                        spiderHouse.setTitle(item.getString("title"));
                        spiderHouse.setStartTime(new Date(item.getLongValue("startTime")));
                        spiderHouse.setEndTime(new Date(item.getLongValue("endTime")));
                        spiderHouses.add(spiderHouse);
                    }

                    ServerManage build = Builder.of(ServerManage::new).with(ServerManage::setSpiderHouses, spiderHouses).build();
                    spiderHouseService.spiderHouseListHandle(build, "127.0.0.1");
                    Thread.sleep(3000); // 为了安全睡一会吧。。。 不知道有没有用。。。。
                    return jsonObject.getIntValue("totalItem");
                }else {
                    logger.info("同步京东列表接口响应异常 content="+httpRespons.getContent());
                }
            }else {
                logger.info("同步京东列表接口调用异常 url="+url);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("同步京东列表数据异常，异常信息："+e.getMessage());
        }
        return 0;
    }

    public int call_gpw(int page, int pageSize, String houseType){
        try {
//            channelId=43不知道是什么
            String info = "{\"channelId\":43,\"itemType\":"+houseType+",\"minPrice\":\"\",\"maxPrice\":\"\",\"pageNumber\":"+page+",\"pageSize\":"+pageSize+"}";
            String url = "https://zc.gpai.net/zc/api/item/list?info="+URLEncoder.encode(info, "utf-8");

//            https://zc.gpai.net/zc/api/item/list?info=%7B%22channelId%22:43,%22itemType%22:1,%22minPrice%22:%22%22,%22maxPrice%22:%22%22,%22pageNumber%22:2,%22pageSize%22:20%7D

            HttpRequest httpRequest = new HttpRequest();
            HttpRespons httpRespons = httpRequest.sendGet(url);
            if (httpRespons != null && httpRespons.getContent() != null){
                JSONObject jsonObject = JSONObject.parseObject(httpRespons.getContent());
                if (jsonObject.containsKey("code") && "0000".equals(jsonObject.getString("code"))){
                    logger.info("同步公拍网列表接口调用成功 page="+page+",pageSize="+pageSize+",itemType="+houseType);
                    JSONArray jsonArray = (JSONArray) CurrencyUtil.readJson(jsonObject, "data.list");

                    List<SpiderHouse> spiderHouses = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject item = jsonArray.getJSONObject(i);
                        SpiderHouse spiderHouse = new SpiderHouse();
                        spiderHouse.setHouseCode(item.getString("id"));
                        spiderHouse.setProvince(item.getString("areaName"));
//                        spiderHouse.setCity();
//                        https://zc.gpai.net/zc/detail?id=3060554
                        spiderHouse.setAuctionUrl("https://zc.gpai.net/zc/detail?id="+spiderHouse.getHouseCode());
                        spiderHouse.setStatus(houseStatusGpwHandle(item.getIntValue("itemStatus")));
                        spiderHouse.setHouseType("住宅用房");   // TODO 都是房产  暂时就写死一个类型了   从详情中获取到则更新
                        spiderHouse.setOrigin(OriginName.GPW.getValue());
                        // TODO 注释掉的是列表里没有的
//                        spiderHouse.setAssessmentPrice(item.getInteger("assessmentPrice"));
//                        spiderHouse.setCurrentPrice(item.getInteger("currentPrice"));
//                        spiderHouse.setDiscountRate(item.getBigDecimal("discountRate"));
//                        spiderHouse.setEnsurePrice(item.getInteger("ensurePrice"));
//                        spiderHouse.setMarketPrice(item.getInteger("marketPrice"));
                        spiderHouse.setMinPrice(item.getLong("startPrice"));
//                        spiderHouse.setCourt(item.getString("shopName"));
                        spiderHouse.setTitle(item.getString("itemName"));
                        spiderHouse.setAddress(spiderHouse.getTitle());
                        spiderHouse.setStartTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, item.getString("beginTime")));
                        spiderHouse.setEndTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, item.getString("endTime")));

                        spiderHouses.add(spiderHouse);
                    }

                    ServerManage build = Builder.of(ServerManage::new).with(ServerManage::setSpiderHouses, spiderHouses).build();
                    spiderHouseService.spiderHouseListHandle(build, "127.0.0.1");
                    Thread.sleep(1000); // 为了安全睡一会吧。。。 不知道有没有用。。。。
                    return Integer.parseInt(CurrencyUtil.readJson(jsonObject, "data.pageCount").toString());
                }else {
                    logger.info("同步公拍网列表接口响应异常 content="+httpRespons.getContent());
                }
            }else {
                logger.info("同步公拍网列表接口调用异常 url="+url);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("同步公拍网列表数据异常，异常信息："+e.getMessage());
        }
        return 0;
    }

    public int call_zppt(int page, int pageSize, String houseType){

        try {
            String url = "https://paimai.caa123.org.cn/paimai-web/ws/0.1/lots?start="+page+"&count="+pageSize+"&standardType=6&secondaryType="+houseType+"&time="+System.currentTimeMillis()+"&_="+System.currentTimeMillis();
//            https://paimai.caa123.org.cn/paimai-web/ws/0.1/lots?start=1&count=20&standardType=6&secondaryType=1&time=1689342829953&_=1689342829886

            HttpRequest httpRequest = new HttpRequest();
            HttpRespons httpRespons = httpRequest.sendGet(url);
            if (httpRespons != null && httpRespons.getContent() != null){
                JSONObject jsonObject = JSONObject.parseObject(httpRespons.getContent());
                if (jsonObject.containsKey("items")){
                    logger.info("同步中拍平台列表接口调用成功 page="+page+",pageSize="+pageSize+",itemType="+houseType);
                    JSONArray jsonArray = jsonObject.getJSONArray("items");

                    List<SpiderHouse> spiderHouses = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject item = jsonArray.getJSONObject(i);
                        SpiderHouse spiderHouse = new SpiderHouse();

                        spiderHouse.setExt1(item.getString("meetId"));  // 这个不知道干啥的 就放这吧  跳转详情需要带着
                        spiderHouse.setExt2(item.getString("onLookerCount")); // 这个放围观数量了   因为详情没有关注和提醒 所以直接在列表里拿下围观就行了

                        spiderHouse.setHouseCode(item.getString("id")+spiderHouse.getExt1());

                        // TODO 需要处理的块
//                        spiderHouse.setProvince();
//                        spiderHouse.setCity();
//                        https://paimai.caa123.org.cn/pages/lots/profession.html?lotId=1587188&meetId=206611
                        spiderHouse.setAuctionUrl("https://paimai.caa123.org.cn/pages/lots/profession.html?lotId="+item.getString("id")+"&meetId="+spiderHouse.getExt1());


                        spiderHouse.setStatus(houseStatusZpptHandle(item.getIntValue("status")));
                        spiderHouse.setHouseType(houseTypeZpptHandle(houseType));
                        spiderHouse.setOrigin(OriginName.ZPPT.getValue());

                        // TODO 注释掉的是列表里没有的
//                        spiderHouse.setAssessmentPrice(item.getInteger("assessmentPrice"));
                        spiderHouse.setCurrentPrice(item.getLong("nowPrice"));
//                        spiderHouse.setDiscountRate(item.getBigDecimal("discountRate"));
//                        spiderHouse.setEnsurePrice(item.getInteger("ensurePrice"));
//                        spiderHouse.setMarketPrice(item.getInteger("marketPrice"));
                        spiderHouse.setMinPrice(item.getLong("startPrice"));
                        spiderHouse.setCourt(item.getString("companyName"));
                        spiderHouse.setTitle(item.getString("name"));
//                        spiderHouse.setAddress(spiderHouse.getTitle());  // 从详情中爬取
                        spiderHouse.setStartTime(new Date(item.getLongValue("startTime")));
                        spiderHouse.setEndTime(new Date(item.getLongValue("endTime")));
                        spiderHouses.add(spiderHouse);
                    }

                    ServerManage build = Builder.of(ServerManage::new).with(ServerManage::setSpiderHouses, spiderHouses).build();
                    spiderHouseService.spiderHouseListHandle(build, "127.0.0.1");
                    Thread.sleep(1000); // 为了安全睡一会吧。。。 不知道有没有用。。。。
                    return jsonObject.getIntValue("totalCount");
                }else {
                    logger.info("同步中拍平台列表接口响应异常 content="+httpRespons.getContent());
                }
            }else {
                logger.info("同步中拍平台列表接口调用异常 url="+url);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("同步中拍平台列表数据异常，异常信息："+e.getMessage());
        }
        return 0;
    }


    public String houseTypeJdHandle(String houseType){
        return "101".equals(houseType) ? "住宅用房"
                : "102".equals(houseType) ? "商业用房"
                : "103".equals(houseType) ? "工业用房"
                : "104".equals(houseType) ? "其他用房"
                : "未知";
    }

    public String houseStatusJdHandle(int auctionStatus, int displayStatus, int bidCount){
        return auctionStatus == 0 && displayStatus == 1 ? ForeclosedHouseStatus.TODO.getValue()
                : auctionStatus == 1 && displayStatus == 1 ? ForeclosedHouseStatus.DOING.getValue()
                : auctionStatus == 2 && displayStatus == 1 && bidCount > 0? ForeclosedHouseStatus.DONE.getValue()
                : auctionStatus == 2 && displayStatus == 1 && bidCount == 0? ForeclosedHouseStatus.FAILURE.getValue()
                : auctionStatus == 2 && displayStatus == 6 ? ForeclosedHouseStatus.BREAK.getValue()
                : auctionStatus == 0 && displayStatus == 5 ? ForeclosedHouseStatus.REVOCATION.getValue()
                : auctionStatus == 2 && displayStatus == 7 ? ForeclosedHouseStatus.STOP.getValue()
                : "未知";
    }

    public String houseStatusGpwHandle(int itemStatus){
        return itemStatus == 4 ? ForeclosedHouseStatus.TODO.getValue()
                : itemStatus == 5 ? ForeclosedHouseStatus.DOING.getValue()
                : itemStatus == 7 ? ForeclosedHouseStatus.DONE.getValue()
                : itemStatus == 8 ? ForeclosedHouseStatus.FAILURE.getValue()
                : itemStatus == 9 ? ForeclosedHouseStatus.REVOCATION.getValue()
                : itemStatus == 10 ? ForeclosedHouseStatus.STOP.getValue()
                : "未知";
    }

    public String houseTypeZpptHandle(String houseType){
        return "1".equals(houseType) ? "住宅用房"
                : "2".equals(houseType) ? "商业用房"
                : "3".equals(houseType) ? "工业用房"
                : "4".equals(houseType) ? "其他用房"
                : "未知";
    }

    public String houseStatusZpptHandle(int status){
        return status == 0 ? ForeclosedHouseStatus.TODO.getValue()
                : status == 1 ? ForeclosedHouseStatus.DOING.getValue()
                : status == 3 ? ForeclosedHouseStatus.DONE.getValue()
                : status == 2 ? ForeclosedHouseStatus.FAILURE.getValue()
                : status == 5 ? ForeclosedHouseStatus.REVOCATION.getValue()
                : "未知";
    }


    public static void main(String[] args) throws Exception{
//        System.out.println(URLDecoder.decode("%7B\"channelId\":43,\"itemType\":1,\"minPrice\":\"\",\"maxPrice\":\"\",\"pageNumber\":2,\"pageSize\":20%7D", "utf-8"));


        String a = "https://api.m.jd.com/api?appid=paimai&functionId=paimai_unifiedSearch&body=%7B%22investmentType%22%3A%22%22%2C%22apiType%22%3A12%2C%22page%22%3A1%2C%22pageSize%22%3A1%2C%22keyword%22%3A%22%E7%A6%8F%E8%A5%BF%E8%B7%AF16%E5%8F%B73502%E6%88%BF%22%2C%22provinceId%22%3A19%2C%22cityId%22%3A%22%22%2C%22countyId%22%3A%22%22%2C%22multiPaimaiStatus%22%3A%220%2C1%22%2C%22multiDisplayStatus%22%3A%22%22%2C%22multiPaimaiTimes%22%3A%22%22%2C%22childrenCateId%22%3A%22%22%2C%22currentPriceRangeStart%22%3A%22%22%2C%22currentPriceRangeEnd%22%3A%22%22%2C%22timeRangeTime%22%3A%22endTime%22%2C%22timeRangeStart%22%3A%22%22%2C%22timeRangeEnd%22%3A%22%22%2C%22loan%22%3A%22%22%2C%22purchaseRestriction%22%3A%22%22%2C%22orgId%22%3A%22%22%2C%22orgType%22%3A%22%22%2C%22sortField%22%3A8%2C%22projectType%22%3A1%2C%22reqSource%22%3A0%2C%22labelSet%22%3A%22%22%2C%22publishSource%22%3A%22%22%2C%22defaultLabelSet%22%3A%22%22%7D&clientVersion=paimai-h5-1.0.0&client=paimai-h5&t=1721954925374&h5st=20240726084845379%3Btznm6g55it9tii59%3B106e8%3Btk03w637e1a4e18nBLg76fBlT120JfQYe-mCrXRfvo8gs-EbBDU7v06DabOZHNa1ney78CED7Wr1H5fMnXaIk9B35NtI%3B32bc5a2ab83289287c08644a32e9ff4e%3B4.7%3B1721954925379%3BUOGI0N27YGd07jVFcO1nIQxzy8ULyp2RkxQar5FavGELe-SUOHdoeGVhCjOx99E9DpNVFYR-sxdR_FK10j6KGHIvVpKaWKsLr6xweTq7N1y8hsyiGJsrBA6Yh73RZ3p26C-75R9vM-Mfc9YmM7vP6zVNRO-VGtA8x9Dg28epV1GmhAQvKHY6xg-DXu7GaN1L9i5EjCCv6YcetHKuamAN-tMvAwScsP4kKNXMwDjK33y2IGgbgsAfa2fV3NG9kLVKbTrkcgaaP5sOLg17qAArrj5Gt46lZt-I04Cz-3MzWk2-CdGmYOeJ1j5Ok_tadIckFg4CY53VYs6qiz_Kv1PhWs5RggE7nDk8PeheJO0dl8zjLad9Prk3hGJ0DQIeqffFGvzEemLTD52YgeDqWQHLXbk3%3B71fb3d11de840b9c60c8244cc9ab14ef&x-api-eid-token=jdd03EU7PJ4SNO3N5D6MIMMMBBHVWL62CDFTT3V22SFVEEIYPYM5Z4UPY5CH3ULATT6F2ZMFGIOAXQR4DCUPV4SIF57XJHAAAAAMQ5R76U3QAAAAACRA3OSQPSELQKIX";

        System.out.println(URLDecoder.decode(a));




//        {"investmentType":"","apiType":12,"page":1,"pageSize":40,"keyword":"","provinceId":19,"cityId":1601,"countyId":3634,"multiPaimaiStatus":"","multiDisplayStatus":"","multiPaimaiTimes":"","childrenCateId":"101","currentPriceRangeStart":"","currentPriceRangeEnd":"","timeRangeTime":"endTime","timeRangeStart":"","timeRangeEnd":"","loan":"","purchaseRestriction":"","orgId":"","orgType":"","sortField":8,"projectType":1,"reqSource":0,"labelSet":"","publishSource":""}
    }

}
